import CreateMenuTransfer from '../components/CreateMenuTransfer'
import React, {useState, useRef, useEffect} from 'react'
import {PageHeaderWrapper} from '@ant-design/pro-layout'
import ProTable, {ProColumns, ActionType} from '@ant-design/pro-table'
import {Form, Input, Divider, message, Button, Modal, Row, Col, Popconfirm} from 'antd'
import {connect, history} from 'umi'
import {
  addRoleInterface,
  getRolePageList,
  deleteUserRole,
  updateRoleMenu,
  updateRoleFunc,
  getMenuEntityList
} from '../service'
import {deleteTransfer} from "@/pages/Personnel/Transfer/service";

const {TextArea} = Input;

const TableList = (props) => {
  const actionRef = useRef();
  const [done, setDone] = useState(false);
  const [visible, setVisible] = useState(null);
  const [addRoleVisible, setAddRoleVisible] = useState(null);
  const [current, setCurrent] = useState(undefined);
  const [type, setType] = useState(null);
  const [form] = Form.useForm();
  const [operateType, setOperateType] = useState(null);
  const [title, setTitle] = useState('');
  const [roleInfo, setRoleInfo] = useState({});
  const [allMenus, setAllMenus] = useState([]);
  const [allFunc, setAllFunc] = useState([]);


  useEffect(() => {
    const setMenuList = (list,setList=[]) => {
      list.forEach(item => {
        setList.forEach(menuItem => {
          if (item.parentId === menuItem.menuId && !item.hasAdd && item.parentId !== '0') {
            let name = menuItem.parentId === '0' ? item.name : `${menuItem.name} / ${item.name}`;
            let m = {...item, name};
            setList.push(m);
            item.hasAdd = true;
            if (setList.length < list.length)
              setMenuList(list);
          }
        });
      });
    };
    getMenuEntityList('1').then(res => {
      let menuList = res.filter(item => item.parentId === '0');
      setMenuList(res,menuList);
      setAllMenus(menuList);
    });
    getMenuEntityList('2').then(res => {
      setAllFunc(res);
    });
  },[]);

  const showMenu = (roleInfo, type) => {
    setVisible(true);
    setType(type);
    setCurrent(roleInfo);
  };

  const handleCancel = () => {
    setCurrent(null);
    setVisible(false);
  };

  const addRole = () => {
    setAddRoleVisible(true);
    setTitle('添加角色');
    setOperateType('add');
    setRoleInfo(null);
  };

  const addRoleOk = values => {
    setAddRoleVisible(false);
    let data = values;
    if (operateType === 'update')
    data.roleId = roleInfo.roleId;
    addRoleInterface(data).then(r => {
      if (r.flag) {
        message.success(`${operateType === 'update' ? '编辑' : '新增'}角色成功。`);
      } else {
        message.error(r.error);
      }
      actionRef.current.reload();
      form.resetFields();
    })
  };

  const showUpdate = record => {
    setAddRoleVisible(true);
    setTitle('编辑角色');
    form.setFieldsValue(record);
    setOperateType('update');
    setRoleInfo(record);
  };

  const addRoleCancel = e => {
    setAddRoleVisible(false);
    form.resetFields();
  };

  const delRole = (value) => {
    deleteUserRole(value.roleId).then(r => {
      if (r.flag) {
        message.success(`删除角色成功。`);
      } else {
        message.error(`删除角色失败。`);
      }
      actionRef.current.reload();
    })
  };

  const handleSubmit = (values, type) => {
    setDone(true);
    setCurrent(null);
    setVisible(false);
    if (type === '2') {
      updateRoleFunc(values).then(r => {
        if (r.flag) {
          message.success(`操作成功。`);
        } else {
          message.error(`操作失败。`);
        }
      })
    } else {
      updateRoleMenu(values).then(r => {
        if (r.flag) {
          message.success(`操作成功。`);
        } else {
          message.error(`操作失败。`);
        }
      })
    }

  };

  const columns = [
    {
      title: '序号',
      render: (text, record, index) => `${index + 1}`,
      hideInSearch: true,
      dataIndex: 'roleId',
      align: 'center',
    },
    {
      title: '角色名称',
      dataIndex: 'roleName',
      align: 'center',
    },
    {
      title: '角色中文名称',
      dataIndex: 'name',
      align: 'center',
    },
    {
      title: '备注',
      hideInSearch: true,
      dataIndex: 'remark',
      align: 'center',
    },

    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      align: 'center',
      width: '20%',
      render: (item, record) => (
        <>
          {<a onClick={() => showMenu(record, '1')}>分配菜单</a>}
          {<Divider type="vertical"/>}
          {<a onClick={() => showMenu(record, '2')}>分配功能</a>}
          {<Divider type="vertical"/>}
          {<a onClick={() => showUpdate(record)}>编辑</a>}
          {<Divider type="vertical"/>}
          {<Popconfirm title={`是否确认删除?`} onConfirm={() => delRole(record)} okText="是" cancelText="否">
            <a>删除</a>
          </Popconfirm>}
        </>
      ),
    },
  ];


  return (
    <PageHeaderWrapper>
      <ProTable
        actionRef={actionRef}
        rowKey="roleId"
        request={(params) => getRolePageList(params)}
        toolBarRender={(action, {selectedRows}) => [
          <Button type="primary" onClick={() => addRole()}>新建</Button>
        ]}
        columns={columns}
      />
      <CreateMenuTransfer
        done={done}
        current={current}
        visible={visible}
        allMenus={allMenus}
        allFunc={allFunc}
        onCancel={handleCancel}
        onSubmit={handleSubmit}
        type={type}
      >
      </CreateMenuTransfer>

      <Modal
        title={title}
        visible={addRoleVisible}
        footer={null}
        closable={false}
      >
        <Form
          form={form}
          name="normal_login"
          className="login-form"
          onFinish={addRoleOk}
        >
          <Form.Item name="roleName">
            <Input placeholder="英文角色名"/>
          </Form.Item>
          <Form.Item name="name">
            <Input placeholder="中文角色名"/>
          </Form.Item>
          <Form.Item name="remark">
            <TextArea rows={4} placeholder="备注"/>
          </Form.Item>
          <Row justify='end' gutter={16}>
            <Col className="gutter-row" style={{paddingBottom: '20px'}}>
              <Button style={{marginRight: '12px'}} onClick={addRoleCancel}>取消</Button>
              <Button type="primary" htmlType="submit">保存</Button>
            </Col>
          </Row>

        </Form>
      </Modal>

    </PageHeaderWrapper>
  )
};

export default connect(({}) => ({}))(TableList)
